package com.heatup.apt.management.service.cashcard;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;
import com.heatup.apt.common.constants.CashcardConstants;
import com.heatup.apt.common.dao.CashcardDetailMapper;
import com.heatup.apt.common.dao.CashcardInfoMapper;
import com.heatup.apt.common.dao.CouponCheckMapper;
import com.heatup.apt.common.util.CouponUtil;
import com.heatup.apt.management.util.ExcelDocumentor;
import com.heatup.apt.management.util.GenerateShortUrlUtil;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.CashcardDetail;
import com.heatup.apt.model.CashcardDetailApiResultModel;
import com.heatup.apt.model.CashcardInfo;
import com.heatup.apt.model.coupon.CouponCheck;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 储值卡服务实现类
 *
 * @author: maxxiang
 * @create: 2016-12-16
 */
@Service
public class CashcardServiceImpl extends SuperServiceImpl<CashcardInfoMapper,CashcardInfo> implements CashcardService {

    @Autowired
    CashcardInfoMapper cashcardInfoMapper;

    @Autowired
    CashcardDetailMapper cashcardDetailMapper;
	
    @Autowired
    CouponCheckMapper couponCheckMapper;
    /**
     * 储值卡券查询
     *
     * @param id 主键
     * @return
     */
    @Override
    public CashcardInfo queryById(Integer id) {
        return cashcardInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 检查储值卡券是否存在名称相同时 是否有正在上架中的
     *
     * @param info
     * @return true 存在/false 不存在
     */
    @Override
    public boolean checkByName(CashcardInfo info) {
    	CashcardInfo infoDB = cashcardInfoMapper.selectByChangeCode(info.getCashcardCode());
        if (infoDB !=null ) {
            return true;
        }
        return false;
    }
    
    /**
     * 保存储值卡 券 信息
     *
     * @param info
     * @param userName
     * @return
     */
    @Override
    public int saveCashcard(CashcardInfo info, String userName) {
        if (info == null)
            return 0;
        int result;
        if (info.getId() == null) {
        	if(info.getIsOneVote() == null){
        		info.setIsOneVote(1);
        	}
        	info.setCashcardStatus(1);
        	info.setCreateBy(userName);
        	info.setCreateTime(new Date());
            result = cashcardInfoMapper.insertSelective(info);
        } else {
        	info.setUpdatedBy(userName);
        	info.setUpdatedTime(new Date());
            result = cashcardInfoMapper.updateSelectiveById(info);
        }
        return result;
    }
    
    /**
     * 查询储值卡 券校验人列表
     *
     * @return
     */
    @Override
    public List<CouponCheck> queryAllCashcardCheckList() {
        return couponCheckMapper.queryAllCheckList(1); //这里共用校验人的方法
    }
    
    /**
     * 更新优惠券上线
     *
     * @param id 主键
     * @param checkName 审核人
     * @param checkPhone 手机号
     * @return
     */
    @Override
    public int updateCashcardToOnline(Integer id, String checkName, String checkPhone) {
        CashcardInfo info = cashcardInfoMapper.selectByPrimaryKey(id);
        info.setCheckName(checkName);
        info.setCheckPhone(checkPhone);
        info.setCashcardStatus(CashcardConstants.CashcardStatus_Online);
        info.setCheckTime(new Date());
        return cashcardInfoMapper.updateSelectiveById(info);
    }

    /**
     * 更新储值卡作废
     *
     * @param id 主键
     * @return
     */
    @Override
    public int updateCashcardToOffline(Integer id) {
        //作废还未领取的储值卡
        cashcardDetailMapper.updateCashcardToOfflineByCashcardId(id);
        CashcardInfo info = cashcardInfoMapper.selectByPrimaryKey(id);
        info.setCashcardStatus(CashcardConstants.CashcardStatus_del);
        return cashcardInfoMapper.updateSelectiveById(info);
    }

	@Override
	public Map<String, Object> queryCashcardInfoPage(Map<String, Object> map) {
		Integer pageNo = (Integer) map.get("pageNo");
		Integer pageSize = (Integer) map.get("pageSize");
		String checkName = (String) map.get("checkName");
		if("all".equals(checkName)){
			map.put("checkName",null);
		}
		// 操作人list
		Map<String, Object> responseMap = new HashMap<String,Object>();
		List<CouponCheck> listCheck = couponCheckMapper.queryAllCheckList(1);
		Page<CashcardInfo> page = new Page<>(pageNo,pageSize);
		List<CashcardInfo> listC = cashcardInfoMapper.queryCashcardInfoPage(page, map);
		page.setRecords(listC);
		map.put("list",page.getRecords());
		map.put("pageCount",page.getTotal());
		map.put("checkList",listCheck);
		page = new Page<>(1,5000);
		map.put("listAll",cashcardInfoMapper.queryCashcardInfoPage(page, map));
		if("all".equals(checkName)){
			map.put("checkName","all");
		}
		return map;
	}

	@Override
	public String downloadCashCard(List<CashcardInfo> list) {
		String downloadPath = ManageConfigPropertiesUtil.getString("uploadImagDir");
		String fileName = "cashCardInfo" + System.currentTimeMillis() + ".xls";

		//创建目录
		File dirFile = new File(downloadPath);
		if (dirFile.exists()) {
			if (!dirFile.isDirectory()) {
				dirFile.mkdir();
			}
		} else {
			dirFile.mkdir();
		}
		
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("id", "储值卡批次");
		columns.put("cashcardName", "储值卡名字");
		columns.put("changeBeginDate", "有效期");
		columns.put("createBy", "创建人");
		columns.put("checkName", "验证人");
		columns.put("createTime", "新增时间");
		columns.put("maxCount", "生成数量");
		columns.put("cashcardAmt", "发放金额");
		columns.put("getedCount", "已兑人数");
		columns.put("cashcardStatus", "状态");
		ExcelDocumentor documentor = new ExcelDocumentor();
		documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		return fileName;
	}
	
	/**
	 * 查看储值卡明细
	 */
	@Override
	public Map<String, Object> quertCashCardDetailByCardId(Map<String, Object> map) {
		Integer pageNo = (Integer) map.get("pageNo");
		Integer pageSize = 10;
		Integer cardId = (Integer) map.get("cashcard_id");
		Page<CashcardDetail> pageD = new Page<>(pageNo,pageSize);
		CashcardInfo cashcardInfo = cashcardInfoMapper.selectById(cardId);
		List<CashcardDetail> listD = cashcardDetailMapper.quertCashcardDetailPage(pageD,map);
		pageD.setRecords(listD);
		map.put("listDetail", listD);
		map.put("cashcardInfo",cashcardInfo);
		map.put("pageCount",pageD.getTotal());
		return map;
	}
	
	/**
	 * 下载储值卡详情
	 */
	@Override
	public Map<String, Object> downloadDetail(Integer cashCardId) {
		// cashCardId
		CashcardInfo cashcardInfo = cashcardInfoMapper.selectById(cashCardId);
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		Map<String,Object> resultMap = new HashMap<String,Object>();
		paramsMap.put("cashcardId", cashcardInfo.getId());
		paramsMap.put("isUsed", 0);
		paramsMap.put("isValid", 1);
		// 如果不存在就直接返回
		if(cashcardInfo != null){
			// 查看生成最大数量
			if(cashcardInfo.getMaxCount() > 0){
				int detailCount = cashcardDetailMapper.queryCashcardDetailCount(paramsMap);
				if(detailCount < 1){
					List<CashcardDetail> listD = new ArrayList<CashcardDetail>();
					for(int i = 0 ;i<cashcardInfo.getMaxCount();i++){
						String code = cashcardCode(cashcardInfo.getId());
						CashcardDetail cashcardDetail  = new CashcardDetail();
						cashcardDetail.setCashcardId(cashcardInfo.getId());
						cashcardDetail.setIsUsed(0);
						cashcardDetail.setIsValid(1);
						cashcardDetail.setMakeTime(new Date());
						cashcardDetail.setCashcardCode(code);
						listD.add(cashcardDetail);
					}
					int bool = 0 ;
					// 批量插入
					if(listD.size() > 0){
						bool = cashcardDetailMapper.insertCashCardDetailBatch(listD);
						logger.info("============================ insert cashcardDetail data =====================bool:"+bool);
					}
					
				}
			}
		}else{
			resultMap.put("msg", "没有储值卡信息");
			resultMap.put("result", "error");
			return resultMap;
		}
		List<CashcardDetailApiResultModel> listApiD = cashcardDetailMapper.queryCashcardDetailModel(cashcardInfo.getId());
		//TODO:这里的URL是优惠券的url到时候换成储值卡的url
		String couponCodeUrl = ManageConfigPropertiesUtil.getString("cashcard_code_url");
		if(listApiD.size() > 0){
			for(CashcardDetailApiResultModel api:listApiD){
				String coupon_code_url= couponCodeUrl.replace("{tempNum}",api.getCashcardCode());
				api.setCashcardCodeUrl(coupon_code_url);
				String shor_coupon_url = GenerateShortUrlUtil.generateShortUrl(coupon_code_url);
				int num = 0 ;
				while (true) {
					shor_coupon_url = GenerateShortUrlUtil.generateShortUrl(coupon_code_url);
					num= num ++ ;
					if ((shor_coupon_url != null && !"".equals(shor_coupon_url)) || num>2) {
						break;
					}
				}
				api.setCashcardShortUrl(shor_coupon_url);
			}
			String fileName = this.downloadCashcardDetail(listApiD);
			resultMap.put("fileName", fileName);
			resultMap.put("result", "success");
			resultMap.put("msg", "export success");
		}else{
			resultMap.put("result", "error");
			resultMap.put("msg", "没有储值卡数据");
		}
		return resultMap;
	}
	
	/**
	 * 生成储值卡兑换码
	 * @return
	 */
	public String cashcardCode(Integer cashcardId){
		String cashcardCode = null;
		CashcardInfo cashcardInfo = cashcardInfoMapper.selectById(cashcardId);
		if(cashcardInfo == null){
			return null;
		}
		if(cashcardInfo.getGetMode() == 1 ){
			return cashcardInfo.getCashcardCode();
		}
        // 从数据库查询出是否存在兑换码，如果有责从新生成。
        while (true) {
        	cashcardCode = CouponUtil.generatorCoupinCode(cashcardId);
            CashcardDetail cashcardDetail = cashcardDetailMapper.selectByChangeCode(cashcardCode);
            logger.info("======================cashcardDetail:"+cashcardDetail+"=========================");
            if (cashcardDetail == null) {
                break;
            }
        }
        logger.info("====================cashcardCode:"+cashcardCode+"===========================");
        return cashcardCode;
	}
	
	/**
	 * 储值卡明细下载
	 * @param list
	 * @return
	 */
	public String downloadCashcardDetail(List<CashcardDetailApiResultModel> list) {
		String downloadPath = ManageConfigPropertiesUtil.getString("uploadImagDir");
		String fileName = "cashcardDetail" + System.currentTimeMillis() + ".xls";

		//创建目录
		File dirFile = new File(downloadPath);
		if (dirFile.exists()) {
			if (!dirFile.isDirectory()) {
				dirFile.mkdir();
			}
		} else {
			dirFile.mkdir();
		}
		
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("id", "明细id");
		columns.put("cashcardId", "储值卡批次id");
		columns.put("cashcardCode", "储值卡兑换码");
		columns.put("makeTime", "生成时间");
		columns.put("isUsed", "是否已使用");
		columns.put("isValid", "是否有效");
		columns.put("cashcardCodeUrl", "长连接");
		columns.put("cashcardShortUrl", "短连接");
		ExcelDocumentor documentor = new ExcelDocumentor();
		documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		return fileName;
	}
	
	
}
